#include<iostream>
#include"Connection.hpp"
#include <arpa/inet.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include"Log.hpp"
#include<string.h>
#include<errno.h>
#include"TcpServer.hpp"
#include"Handler.hpp"
#include"Comm.hpp"
class Accepter
{
public:
    Accepter() {}

    void AcceptConnection(Connection* conn)
    {
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(conn->GetFd(), (struct sockaddr *)&peer, &len);
            if (sockfd > 0)
            {
                lg.LogMessage(Info, "create new sockfd suucess,sockfd is: %d\n", sockfd);
                SetNonBlock(sockfd);
                auto recv = std::bind(&Handler::Recv, std::placeholders::_1);
                auto send = std::bind(&Handler::Send, std::placeholders::_1);
                auto except = std::bind(&Handler::Except, std::placeholders::_1);
                auto new_conn = ConnectionFactory::BuildNormalConnection(sockfd, recv, send, except, EPOLLIN | EPOLLET, conn->_R);
                conn->_R->AddConnection(new_conn);
            }
            else
            {
                if(errno==EAGAIN)
                break;
                else if(errno==EINTR)
                continue;
                else
                {
                    lg.LogMessage(Error, "create new sockfd error,%s : %d\n", strerror(errno), errno);
                    break;
                }
            }
        }
    }

    ~Accepter() {}

private:
};